import { LockOutlined, MailOutlined, UserOutlined, SafetyOutlined } from '@ant-design/icons';
import { message, Tabs } from 'antd';
import React, { useEffect, useState } from 'react';
import ProForm, { ProFormCaptcha, ProFormText, LoginForm } from '@ant-design/pro-form';
import { useIntl, history, FormattedMessage, useModel } from 'umi';
// import Footer from '@/components/Footer';
import { login, getEmailCaptcha, getCaptcha, getSettingsInfo } from '@/services/common';
import { RSAencrypt } from '@/utils/utils';

import styles from './index.less';

const Login: React.FC = () => {
  const [type, setType] = useState<string>('1');
  const [codeImg, setCodeImg] = useState<string>('');
  const [uuid, setUuid] = useState<string>('');
  const [isCan, setIsCan] = useState<boolean>(false);
  const [isTiming, setIsTiming] = useState<boolean>(false);
  const [info, setInfo] = useState<COMMON_API.Settings | undefined>(undefined)
  const [logoUrl, setLogoUrl] = useState<string>('')
  const { initialState, setInitialState } = useModel('@@initialState');
  const [form] = ProForm.useForm();
  const intl = useIntl();

  const fetchCaptcha = async () => {
    const rsp = await getCaptcha();
    if (rsp.code === 0) {
      setCodeImg(rsp.data.img);
      setUuid(rsp.data.uuid);
    }
  };

 const fetchSettings = async () => {
    const rsp = await getSettingsInfo()
    if(rsp.code === 0) {
      setInfo(rsp.data)
      setLogoUrl(rsp.data.logo && rsp.data.logo.startsWith('http') ? rsp.data.logo : window.location.protocol + '//' + window.location.host + ':7001' + rsp.data.logo)
    }
  }

  useEffect(() => {
    fetchCaptcha();
    fetchSettings()
  }, []);

  const changeCaptcha = () => {
    fetchCaptcha();
  };

  const changeEmail = () => {
    if (
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
        form.getFieldValue('email'),
      )
    ) {
      setIsCan(true);
    } else {
      setIsCan(false);
    }
  };

  const fetchUserInfo = async () => {
    const info = await initialState?.fetchUserInfo?.();
    const routers = await initialState?.fetchRouters?.();
    if (info) {
      await setInitialState((s: any) => ({
        ...s,
        currentUser: info.userInfo,
        sysSettings: info.settings,
        menuList: routers?.menuList,
        hasRoute: routers?.hasRoute,
        permsList: routers?.permsList,
        allMenuList: routers?.allMenuList,
      }));
    }
  };

  const handleSubmit = async (values: COMMON_API.LoginParams) => {
    try {
      // 登录
      values.password = RSAencrypt(values.password as string);
      values.type = Number(type);
      if (values.type === 1) {
        values.uuid = uuid;
      }
      const rsp = await login({ ...values });
      if (rsp.code === 0) {
        localStorage.setItem('token', `${rsp.token}`);
        message.success('登录成功');
        await fetchUserInfo();
        /** 此方法会跳转到 redirect 参数所在的位置 */
        if (!history) return;
        const { query } = history.location;
        const { redirect } = query as { redirect: string };
        history.push(redirect || '/');
        return;
      }
      changeCaptcha();
    } catch (error) {
      message.error('登录失败，请重试！');
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          form={form}
          logo={<img alt="logo" src={logoUrl} />}
          title={info?.title_en}
          subTitle={info?.title}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values: COMMON_API.LoginParams) => {
            await handleSubmit(values as COMMON_API.LoginParams);
          }}
        >
          <Tabs activeKey={type} onChange={setType}>
            <Tabs.TabPane
              key="1"
              tab={intl.formatMessage({
                id: 'pages.login.accountLogin.tab',
                defaultMessage: '账户密码登录',
              })}
            />
            <Tabs.TabPane
              key="2"
              tab={intl.formatMessage({
                id: 'pages.login.emailLogin.tab',
                defaultMessage: '邮箱登录',
              })}
            />
          </Tabs>
          {type === '1' && (
            <>
              <ProFormText
                name="user_no"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.username.placeholder',
                  defaultMessage: '请输入账号',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.username.required"
                        defaultMessage="请输入账号!"
                      />
                    ),
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.password.placeholder',
                  defaultMessage: '请输入密码',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.password.required"
                        defaultMessage="请输入密码!"
                      />
                    ),
                  },
                ]}
              />
              <div style={{ display: 'flex' }}>
                <ProFormText
                  name="captchaCode"
                  fieldProps={{
                    size: 'large',
                    prefix: <SafetyOutlined className={styles.prefixIcon} />,
                  }}
                  placeholder={intl.formatMessage({
                    id: 'pages.login.captcha.placeholder',
                    defaultMessage: '请输入验证码',
                  })}
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.login.captcha.required"
                          defaultMessage="请输入验证码！"
                        />
                      ),
                    },
                  ]}
                />
                <div>
                  {codeImg && (
                    <div
                      style={{ cursor: 'pointer' }}
                      title="点击更换验证码"
                      onClick={() => changeCaptcha()}
                      dangerouslySetInnerHTML={{ __html: codeImg }}
                    />
                  )}
                </div>
              </div>
            </>
          )}

          {type === '2' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MailOutlined className={styles.prefixIcon} />,
                }}
                name="email"
                placeholder={intl.formatMessage({
                  id: 'pages.login.emailNumber.placeholder',
                  defaultMessage: '请输入邮箱',
                })}
                onChange={changeEmail}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.emailNumber.required"
                        defaultMessage="请输入邮箱！"
                      />
                    ),
                  },
                  {
                    pattern:
                      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
                    message: (
                      <FormattedMessage
                        id="pages.login.emailNumber.invalid"
                        defaultMessage="邮箱格式错误！"
                      />
                    ),
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <SafetyOutlined className={styles.prefixIcon} />,
                }}
                captchaProps={{
                  size: 'large',
                  disabled: !isCan || isTiming,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.captcha.placeholder',
                  defaultMessage: '请输入验证码',
                })}
                captchaTextRender={(timing: string, count: number) => {
                  setIsTiming(timing ? true : false);
                  if (
                    /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
                      form.getFieldValue('email'),
                    ) &&
                    timing
                  ) {
                    return `${count} ${intl.formatMessage({
                      id: 'pages.getCaptchaSecondText',
                      defaultMessage: '获取验证码',
                    })}`;
                  }

                  return intl.formatMessage({
                    id: 'pages.login.phoneLogin.getVerificationCode',
                    defaultMessage: '获取验证码',
                  });
                }}
                name="captchaCode"
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.captcha.required"
                        defaultMessage="请输入验证码！"
                      />
                    ),
                  },
                ]}
                onGetCaptcha={async () => {
                  if (
                    !/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
                      form.getFieldValue('email'),
                    )
                  ) {
                    message.warning('邮箱格式不正确');
                    return;
                  }
                  const result = await getEmailCaptcha({
                    email: form.getFieldValue('email'),
                  });
                  if (result.code === 0) {
                    message.success(result.msg);
                  } else {
                    setIsCan(true);
                  }
                }}
              />
            </>
          )}
          {/* <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              <FormattedMessage id="pages.login.rememberMe" defaultMessage="自动登录" />
            </ProFormCheckbox>
            <a
              style={{
                float: 'right',
              }}
            >
              <FormattedMessage id="pages.login.forgotPassword" defaultMessage="忘记密码" />
            </a>
          </div> */}
        </LoginForm>
      </div>
      {/* <Footer /> */}
    </div>
  );
};

export default Login;
